package org.example.projecttwo.service.Impl.article;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.projecttwo.entity.article.Article;
import org.example.projecttwo.entity.article.ArticlePartition;
import org.example.projecttwo.entity.dto.content.request.ContentDeleteDTO;
import org.example.projecttwo.entity.dto.content.request.ContentOffShelfDTO;
import org.example.projecttwo.entity.dto.content.response.ArticleDetailVO;
import org.example.projecttwo.mapper.article.ArticleMapper;
import org.example.projecttwo.mapper.article.ArticlePartitionMapper;
import org.example.projecttwo.service.Iarticle.IArticleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * 文章服务实现类
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements IArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private ArticlePartitionMapper partitionMapper;

    @Override
    public IPage<Article> pageByCondition(Page<Article> page, Integer status, String partitionCode,
                                          Integer isFeatured, String keyword, String startTime, String endTime) {

        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();

        // 状态筛选
        if (status != null) {
            queryWrapper.eq(Article::getStatus, status);
        }

        // 分区筛选
        if (partitionCode != null && !partitionCode.isEmpty()) {
            if ("featured".equals(partitionCode)) {
                queryWrapper.eq(Article::getIsFeatured, 1);
            } else {
                queryWrapper.eq(Article::getPartitionCode, partitionCode);
            }
        }

        // 精品筛选
        if (isFeatured != null) {
            queryWrapper.eq(Article::getIsFeatured, isFeatured);
        }

        // 关键词搜索
        if (keyword != null && !keyword.isEmpty()) {
            queryWrapper.and(w -> w.like(Article::getTitle, keyword)
                    .or().like(Article::getContent, keyword));
        }

        // 时间范围筛选
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if (startTime != null && !startTime.isEmpty()) {
            queryWrapper.ge(Article::getCreateTime, LocalDateTime.parse(startTime, formatter));
        }
        if (endTime != null && !endTime.isEmpty()) {
            queryWrapper.le(Article::getCreateTime, LocalDateTime.parse(endTime, formatter));
        }

        // 排序
        queryWrapper.orderByDesc(Article::getCreateTime);

        IPage<Article> result = this.page(page, queryWrapper);

        // 处理返回结果，修正字段值
        result.getRecords().forEach(article -> {
            // 未删除时设置为null
            if (article.getDeleted() != null && article.getDeleted() == 0) {
                article.setDeleted(null);
            }

            // 状态为草稿（0）时，提交审核时间应为null
            if (article.getStatus() != null && article.getStatus() == 0) {
                article.setSubmitAuditTime(null);
            }

            // 非精品文章，FeaturedTime应为null
            if (article.getIsFeatured() != null && article.getIsFeatured() == 0) {
                article.setFeaturedTime(null);
            }

            // 已发布状态必须有发布时间
            if (article.getStatus() != null && article.getStatus() == 2 && article.getPublishTime() == null) {
                // 可根据实际业务设置默认值或抛出异常
                article.setPublishTime(article.getCreateTime());
            }

            // 处理publishStrategy为空的情况
            if (article.getPublishStrategy() != null &&
                    (article.getStatus() == 0 || article.getStatus() == 3)) {  // 草稿或审核未通过
                article.setPublishStrategy(null);
            }
        });

        return result;
    }



    @Override
    public ArticleDetailVO getArticleDetail(Long id) {
        Article article = articleMapper.selectByIdWithAllFields(id);
        if (article == null) {
            return null;
        }

        ArticleDetailVO detailVO = new ArticleDetailVO();
        BeanUtils.copyProperties(article, detailVO);

        // 设置状态名称
        switch (article.getStatus()) {
            case 0:
                detailVO.setStatusName("草稿");
                break;
            case 1:
                detailVO.setStatusName("待审核");
                break;
            case 2:
                detailVO.setStatusName("审核通过");
                break;
            case 3:
                detailVO.setStatusName("审核未通过");
                break;
            case 4:
                detailVO.setStatusName("已下架");
                break;
            default:
                detailVO.setStatusName("未知状态");
        }

        // 查询分区信息
        ArticlePartition partition = partitionMapper.selectById(article.getPartitionCode());
        detailVO.setPartition(partition);

        // 查询统计数据
        Map<String, Integer> statistics = articleMapper.getArticleStatistics(id);
        detailVO.setStatistics(statistics);

        return detailVO;
    }

    @Override
    @Transactional
    public void deleteArticle(Long id, ContentDeleteDTO deleteDTO) {
        Article article = new Article();
        article.setId(id);
        article.setStatus(5);
        article.setDeleteReason(deleteDTO.getDeleteReason());
        article.setDeleteRemark(deleteDTO.getDeleteRemark());
        articleMapper.updateById(article);
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        Article article = new Article();
        article.setId(id);
        article.setStatus(status);

        if (status == 2) { // 审核通过（发布）
            // 若未设置发布时间，默认当前时间
            article.setPublishTime(LocalDateTime.now());
        }

        articleMapper.updateById(article);
    }

    @Override
    @Transactional
    public void unpublishArticle(Long id, ContentOffShelfDTO offShelfDTO) {
        Article article = new Article();
        article.setId(id);
        article.setStatus(4); // 已下架状态
        article.setOffShelfTime(LocalDateTime.now());
        article.setOffShelfReason(offShelfDTO.getOffShelfReason());
        articleMapper.updateById(article);
    }

    @Override
    @Transactional
    public void batchUpdateStatus(List<Long> ids, Integer status) {
        LocalDateTime now = LocalDateTime.now();
        articleMapper.batchUpdateStatus(ids, status, now);
    }

    @Override
    @Transactional
    public void batchUnpublish(List<Long> ids, Integer offShelfReason) {
        articleMapper.batchUnpublish(
                ids,
                4,  // 已下架状态码
                offShelfReason,  // 直接使用原因参数
                LocalDateTime.now()
        );
    }

    @Override
    @Transactional
    public void batchDelete(List<Long> ids, Integer deleteReason, String deleteRemark) {
        articleMapper.batchDelete(ids, 5, deleteReason, deleteRemark);
    }

    @Override
    public void updateFeaturedStatus(Long id, Integer featured) {
        Article article = new Article();
        article.setId(id);
        article.setIsFeatured(featured);
        article.setFeaturedTime(featured == 1 ? LocalDateTime.now() : null);
        articleMapper.updateById(article);
    }

    @Override
    public int countPublishedArticles() {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getStatus, 2)
                .ne(Article::getStatus, 5);
        return Math.toIntExact(articleMapper.selectCount(queryWrapper));
    }

    @Override
    @Transactional
    public void auditArticle(Long id, Integer auditResult, String rejectReason) {
        // 获取当前登录的审核人用户名
        String auditUser = SecurityContextHolder.getContext().getAuthentication().getName();
        articleMapper.auditArticle(id, auditResult, rejectReason, auditUser, LocalDateTime.now());
    }

    @Override
    @Transactional
    public void batchAudit(List<Long> ids, Integer auditResult, String rejectReason) {
        // 获取当前登录的审核人用户名
        String auditUser = SecurityContextHolder.getContext().getAuthentication().getName();
        articleMapper.batchAudit(ids, auditResult, rejectReason, auditUser, LocalDateTime.now());
    }

    @Override
    public Map<String, Integer> getArticleStatistics(Long id) {
        return articleMapper.getArticleStatistics(id);
    }

    @Override
    public List<ArticlePartition> getAllPartitions() {
        LambdaQueryWrapper<ArticlePartition> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ArticlePartition::getEnabled, 1) // 只查询启用的分区
                .orderByAsc(ArticlePartition::getSortOrder);
        return partitionMapper.selectList(queryWrapper);
    }

    @Override
    public void savePartition(ArticlePartition partition) {
        partition.setCreateTime(LocalDateTime.now());
        partition.setUpdateTime(LocalDateTime.now());
        partition.setSortOrder(partition.getSortOrder() != null ? partition.getSortOrder() : 0);
        partition.setEnabled(partition.getEnabled() != null ? partition.getEnabled() : 1);
        partitionMapper.insert(partition);
    }

    @Override
    public void updatePartition(String code, ArticlePartition partition) {
        partition.setCode(code); // 确保编码不变
        partition.setUpdateTime(LocalDateTime.now());
        partitionMapper.updateById(partition);
    }

    @Override
    @Transactional
    public void deletePartition(String code) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getPartitionCode, code)
                .ne(Article::getStatus, 5);

        long count = articleMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new RuntimeException("该分区下存在文章，无法删除");
        }

        LambdaQueryWrapper<ArticlePartition> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ArticlePartition::getCode, code);
        partitionMapper.delete(wrapper);
    }

    @Override
    @Transactional
    public void saveOrUpdatePartitions(List<ArticlePartition> partitions) {
        LocalDateTime now = LocalDateTime.now();
        for (ArticlePartition partition : partitions) {
            partition.setUpdateTime(now);
            if (partitionMapper.exists(new LambdaQueryWrapper<ArticlePartition>()
                    .eq(ArticlePartition::getCode, partition.getCode()))) {
                partitionMapper.updateById(partition);
            } else {
                partition.setCreateTime(now);
                partitionMapper.insert(partition);
            }
        }
    }

    @Override
    public void increaseViewCount(Long id) {
        articleMapper.increaseViewCount(id);
    }

    @Override
    public List<Article> getUserDraftsByUserId(Long userId) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getAuthorId, userId)
                .eq(Article::getStatus, 0) // 只筛选草稿状态（与新闻接口一致）
                .orderByDesc(Article::getUpdateTime);
        return articleMapper.selectList(queryWrapper);
    }

    @Override
    public void deleteDraft(Long id) {
        // 草稿直接物理删除
        articleMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void submitDraftForAudit(Long id, String coverUrl, Integer publishStrategy, String publishTime) {
        LocalDateTime submitTime = LocalDateTime.now();
        articleMapper.submitDraftForAudit(
                id,
                coverUrl,
                publishStrategy,
                publishTime,
                submitTime
        );
    }

    @Override
    public IPage<Article> pageDeletedArticles(Page<Article> page, String keyword) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getStatus, 5); // 5=已删除状态（与新闻保持一致）

        // 关键词搜索（标题匹配）
        if (StringUtils.hasText(keyword)) {
            queryWrapper.like(Article::getTitle, keyword);
        }

        queryWrapper.orderByDesc(Article::getUpdateTime);
        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    public void restoreDeletedArticles(List<Long> ids) {
        // 恢复为草稿状态（0=草稿，与新闻保持一致）
        ids.forEach(id -> {
            Article article = new Article();
            article.setId(id);
            article.setStatus(0); // 状态从“已删除”恢复为“草稿”
            baseMapper.updateById(article);
        });
    }

    @Override
    @Transactional
    public void permanentlyDeleteArticles(List<Long> ids) {
        // 物理删除（从数据库中彻底移除）
        baseMapper.deleteBatchIds(ids);
    }

}